package info.lvcoffee.ethernethelper;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends  PreferenceActivity 
					implements   OnSharedPreferenceChangeListener
{ 
	private String TAG="ethernethelper";
	//是否检测到了网络接口
	private boolean bHaveEth=false;
	
	UsbManager mUsbManager = null;
	
	private List<NetInterfaceInfo>  mListEthInterface;    
	
	private NetInterfaceInfo   mEthInterface=null;
	
	private Handler mHandler=null;
	
	private static final String ACTION_USB_PERMISSION = "info.lvcoffee.ethernethelper.USB_PERMISSION";
//	private  final int HANDLE_MSG_CHECK_NET_ENABLE = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);
		addPreferencesFromResource(R.xml.main_preferences);   	
				
		mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		IntentFilter attachedAndDetachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
		attachedAndDetachedFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		attachedAndDetachedFilter.addAction(ACTION_USB_PERMISSION);
		registerReceiver(mUsbReceiver, attachedAndDetachedFilter);
		
		mHandler=new Handler();

		if(!Utils.getInstance().hasNetcfg())
			Utils.getInstance().copyFiles(this);
	}


	
	private void initView()
	{
		
		Preference preCopyright=(Preference)findPreference("app_copyright");
		preCopyright.setSummary(String.format(
				getResources().getString(R.string.app_copyright),getAppVersionName(this)));
	
		ListPreference preList=(ListPreference)findPreference("ip_setting_list");
		preList.setSummary(preList.getEntry());

    	if (!Utils.getInstance().hasRootPermission())
    	{
    		openNotRootDialog();
    		return;
    	}
    	
		  //初始化IP信息
		 initIpInfoSummary();
		 
		//是否有USB网卡插在机器上
		mListEthInterface=Utils.getInstance().getNetInterface();
		bHaveEth=false;
		String saveInterface=Utils.getInstance().readEthInterface(this);
		if(saveInterface!="")
		{
			NetInterfaceInfo  ifInfo=findInterfaceByName(saveInterface,mListEthInterface);
			if(ifInfo!=null)
			{				
				mEthInterface=ifInfo;
				if(mEthInterface.getIfState().equals("UP"))
					 bHaveEth=true;
			}
		}
		
		Preference enEth=(Preference)findPreference("enable_eth");
		if(bHaveEth)
		{				
			enEth.setSummary(String.format(getResources().getString(R.string.find_eth),saveInterface));
			setIpInfoSummary(mEthInterface);
		}
		else
		{
			//enEth.setChecked(false);
			enEth.setSummary(R.string.not_find_eth);
			enEth.setEnabled(false);
			//enEth.setShouldDisableView(true);
		}
		
		//检测是否开启了网络ADB连接功能
		 checkAdbState();
	  

		 
	  	 if(preList.getEntry().equals("DHCP"))
	  	  {
	  		  setIpState(false);
	  	  }
	  	  else
	  	  {
	  		  setIpState(true);
	  	  }
	}
	
	/*
	 * 在初始化时，更新IP信息显示
	 * 
	 */
	private void initIpInfoSummary()
	{
	  	  EditTextPreference editIpAddrPref=(EditTextPreference)findPreference("ip_address");
	  	  String ipAddress=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_address", "0.0.0.0");
	  	  
	  	  if(Utils.checkIpValid(ipAddress))
	  		  editIpAddrPref.setSummary(ipAddress);
	  	  else
	  	  {
	  		  editIpAddrPref.setSummary("0.0.0.0"); 		 
	  	  }
	
	  	  EditTextPreference editIpMaskPref=(EditTextPreference)findPreference("ip_mask");
	  	  String ipMask=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_mask", "0.0.0.0");
	  	  if(Utils.checkIpValid(ipMask))
	  		  editIpMaskPref.setSummary(ipMask);
	  	  else
	  	  {
	  		  editIpMaskPref.setSummary("0.0.0.0");
	  	  }
	  	  
	
	  	  EditTextPreference editIpGWPref=(EditTextPreference)findPreference("ip_gateway");
	  	  String ipGW=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_gateway", "0.0.0.0");
	  	  if(Utils.checkIpValid(ipGW))
	  		  editIpGWPref.setSummary(ipGW);
	  	  else
	  	  {
	  		  editIpGWPref.setSummary("0.0.0.0");
	  	  }	
	  	  
	}
	
	/*
	 * 开启网卡成功后，设置IP信息显示
	 * 
	 */
	private void setIpInfoSummary(NetInterfaceInfo iface)
	{
	  	  EditTextPreference editIpAddrPref=(EditTextPreference)findPreference("ip_address");	
	  	  editIpAddrPref.setSummary(iface.getIfIpAddr()); 		 
	  	  	
	  	  EditTextPreference editIpMaskPref=(EditTextPreference)findPreference("ip_mask");
	  	  String ipMask=Utils.getInstance().getNetMask(iface.getIfName());	  	
	  	  editIpMaskPref.setSummary(ipMask);	 
	  	  	
	}
	
	
	
	
	@Override
	protected void onResume() 
	{ 
		super.onResume(); 
		// Set up a listener whenever a key changes
		getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this);
		   	
    	initView();

	}
	
	
	@Override
	protected void onPause() {
		super.onPause(); 
		// Unregister the listener whenever a key changes 
		getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this);

	}
/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		getActionBar().setBackgroundDrawable(this.getBaseContext().getResources().
				getDrawable(R.drawable.header));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_about) {
			Intent in=new Intent(this, HelpWeb.class);
			startActivity(in);
			return true;
		}
		else if(id == R.id.action_feedback) {
			FeedbackAgent agent = new FeedbackAgent(this);
			agent.startFeedbackActivity();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}*/

  	private void openNotRootDialog() {
		new AlertDialog.Builder(MainActivity.this)
        .setTitle(getString(R.string.no_root))
        .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	//disable dial tab
            		Preference enEth=(Preference)findPreference("enable_eth");

        			//enEth.setChecked(false);
        			enEth.setSummary(R.string.no_root);
        			enEth.setEnabled(false);
        			enEth.setShouldDisableView(true);
            		
                }
        })
        .show();
   	}	

  	
	/*
	 * 检测是否开启了网络ADB连接功能
	 * 
	 * 
	 */
	private void checkAdbState()
	{
		CheckBoxPreference enAdb=(CheckBoxPreference)findPreference("enable_net_adb");
		enAdb.setSummary(R.string.not_enable_net_adb);
		if(Utils.getInstance().isEnableNetAdb())
		{
			String ipAddr="";
			for(NetInterfaceInfo iter:mListEthInterface)
				if(iter.getIfState().equals("UP")&&(!iter.getIfIpAddr().equals("0.0.0.0")))
				{
					ipAddr=iter.getIfIpAddr();
				
					enAdb.setSummary(String.format(getResources().getString(R.string.net_adb_is_openned),ipAddr));
					//TODO:不知道如何关闭，暂时设成不能关闭
					enAdb.setEnabled(false);
					return;
				}	
			
			//使可以再次开启
			enAdb.setChecked(false);
			enAdb.setEnabled(true);
		}
	}
	
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) 
	{
	      if (preference.getKey().equals("app_copyright")) {
	    	  Uri uri = Uri.parse("https://edwinliu.github.io/");
	    	  Intent it = new Intent(Intent.ACTION_VIEW, uri);  
	    	  startActivity(it);       
	      }	 
	      else if (preference.getKey().equals("ethernet_card_buy")) {
	    	  Uri uri = Uri.parse("http://shop115087930.m.taobao.com/");  
	    	  Intent it = new Intent(Intent.ACTION_VIEW, uri);  
	    	  startActivity(it);       
	      }
	      
	      
	      return false;
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
	{
		if(key.equals("enable_eth"))
		{
	    	  Preference checkPref=(Preference)findPreference("enable_eth");
	    	 // if(checkPref.isChecked())
	    	  {

	    		
				mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
			  			ListPreference preList=(ListPreference)findPreference("ip_setting_list");

						if(preList.getEntry().equals("DHCP"))
							 Utils.getInstance().enableEthernet(mEthInterface.getIfName(), true);
						else
						{
							 Utils.getInstance().enableEthernet(mEthInterface.getIfName(), false);
							 SharedPreferences  sharePref=PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
							 String ipAddr=sharePref.getString("ip_address", "0.0.0.0");
							 String ipMask=sharePref.getString("ip_mask", "0.0.0.0");
							 String ipGateway=sharePref.getString("ip_gateway", "0.0.0.0");
							 Utils.getInstance().setStaticIp(mEthInterface.getIfName(),ipAddr,ipMask,ipGateway);
						}
						
						Utils.getInstance().setDNS(mEthInterface.getIfName());
						
						//check 是否成功
						List<NetInterfaceInfo> ifList=Utils.getInstance().getNetInterface();
						for(NetInterfaceInfo iter:ifList)
						{
							if(mEthInterface.getIfName().equals(iter.getIfName()))
							{
								if(iter.getIfState().equals("UP")&&iter.getIfIpAddr()!="0.0.0.0")
								{
									mEthInterface=iter;
									setIpInfoSummary(mEthInterface);
									Toast.makeText(MainActivity.this, R.string.enable_ethernet_success,
											Toast.LENGTH_LONG).show();
								}
								else
								{
									Toast.makeText(MainActivity.this, R.string.enable_ethernet_fail,
											Toast.LENGTH_LONG).show();
								}
							}
						}
						
					}
				}, 50);
	    	  }
		}else if (key.equals("enable_net_adb")) {
	    	  CheckBoxPreference checkPref=(CheckBoxPreference)findPreference("enable_net_adb");
	    	  if(checkPref.isChecked())
	    	  {
	    		  Utils.getInstance().enableNetAdb();
	    		  checkAdbState();
	    	  }
	    }
		else if(key.equals("ip_setting_list"))
		{
			ListPreference preList=(ListPreference)findPreference("ip_setting_list");

			preList.setSummary(preList.getEntry());

			if(preList.getEntry().equals("DHCP"))
			     setIpState(false);
			else
				setIpState(true);
			
		}else if (key.equals("ip_address")) {
	    	  EditTextPreference editPref=(EditTextPreference)findPreference("ip_address");
	    	  String ip=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_address", "0.0.0.0");
	    	  
	    	  if(Utils.checkIpValid(ip))
	    		  editPref.setSummary(ip);
	    	  else
	    	  {
	    		  editPref.setSummary("0.0.0.0");
	    		  Toast.makeText(this, R.string.ip_error, Toast.LENGTH_LONG).show();
	    	  }
	    }else if (key.equals("ip_mask")) {
	    	  EditTextPreference editPref=(EditTextPreference)findPreference("ip_mask");
	    	  String ip=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_mask", "0.0.0.0");
	    	  if(Utils.checkIpValid(ip))
	    		  editPref.setSummary(ip);
	    	  else
	    	  {
	    		  editPref.setSummary("0.0.0.0");
	    		  Toast.makeText(this, R.string.ip_error, Toast.LENGTH_LONG).show();
	    	  }
	    }else if (key.equals("ip_gateway")) {
	    	  EditTextPreference editPref=(EditTextPreference)findPreference("ip_gateway");
	    	  String ip=PreferenceManager.getDefaultSharedPreferences(this)
						.getString("ip_gateway", "0.0.0.0");
	    	  if(Utils.checkIpValid(ip))
	    		  editPref.setSummary(ip);
	    	  else
	    	  {
	    		  editPref.setSummary("0.0.0.0");
	    		  Toast.makeText(this, R.string.ip_error, Toast.LENGTH_LONG).show();
	    		  
	    	  }
	     }	
	}

	/*
	 * 当DHCP时不可设置
	 * 
	 */
	private void setIpState(boolean bEnable)
	{
	  	  EditTextPreference editIpAddrPref=(EditTextPreference)findPreference("ip_address");
	
	  	  EditTextPreference editIpMaskPref=(EditTextPreference)findPreference("ip_mask");
	
	  	  EditTextPreference editIpGWPref=(EditTextPreference)findPreference("ip_gateway");
	  	  
		  editIpAddrPref.setEnabled(bEnable);
		  editIpMaskPref.setEnabled(bEnable);
		  editIpGWPref.setEnabled(bEnable);
		
	}
	
	/**
	 * 接收USB设备插入和拔出的广播
	 */
	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        Utils.debug(TAG,"mUsbReceiver-" + action);
	        
	        //检测到USB设备拔出
	        if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
	            synchronized (this) {
	                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
	                
	                if((device != null)&&(mEthInterface!=null)){
	                      //	                   	
	                	Utils.debug(TAG,"DEATTCHED-" + device);
	                	//获取网络接口列表
	                	mListEthInterface=Utils.getInstance().getNetInterface();
	                	
	                	boolean bEthRemove=true;
	                	for(NetInterfaceInfo iter:mListEthInterface)
                    	{
	                		 if(iter.getIfName().equals(mEthInterface.getIfName()))
	                		 {
	                			 bEthRemove=false;
	                			 break;
	                		 }
                    	}
	                	
	                	if(bEthRemove)
	                	{
	                		Preference preList=(Preference)findPreference("enable_eth");
	                		//preList.setChecked(false);
	            			preList.setSummary(R.string.not_find_eth);
	            			preList.setEnabled(false);
	            			//preList.setShouldDisableView(true);
	            		  	  EditTextPreference editIpAddrPref=(EditTextPreference)findPreference("ip_address");	
	            		  	  editIpAddrPref.setSummary("0.0.0.0"); 		 
	            		  	  	
	            		  	  EditTextPreference editIpMaskPref=(EditTextPreference)findPreference("ip_mask");	  	
	            		  	  editIpMaskPref.setSummary("0.0.0.0"); 
	                	}
	                  }
	            }
	        }

	        //检测到USB设备插入
			if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
				synchronized (this) {
	                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
	               // if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) 
	                {
	                	
	                    if(device != null){
	                      //
	                    	
	                    	Utils.debug(TAG,"ATTACHED-" + device);
	                    	updateEthInterface();
	                    	
	                    	mHandler.postDelayed(new Runnable() {
	        					
	        					@Override
	        					public void run() {
	        			  			        						
	        						//check 是否成功
	        						List<NetInterfaceInfo> ifList=Utils.getInstance().getNetInterface();
	        						for(NetInterfaceInfo iter:ifList)
	        						{
	        							if(mEthInterface.getIfName().equals(iter.getIfName()))
	        							{
	        								if(iter.getIfState().equals("UP")&&iter.getIfIpAddr()!="0.0.0.0")
	        								{
	        									mEthInterface=iter;
	        									setIpInfoSummary(mEthInterface);
	        									Toast.makeText(MainActivity.this, R.string.enable_ethernet_success,
	        											Toast.LENGTH_LONG).show();
	        								}
	        								else
	        								{
	        									Toast.makeText(MainActivity.this, R.string.enable_ethernet_fail,
	        											Toast.LENGTH_LONG).show();
	        								}
	        							}
	        						}
	        						
	        					}
	        				}, 3000);
	                   }
	                } 
	              /*  else {
	            		PendingIntent mPermissionIntent;
	            		mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this,
	            						0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_ONE_SHOT);	                    
	                    mUsbManager.requestPermission(device, mPermissionIntent);
	                    
	                }		*/			
	
				}
			}
		
			// 获得了用户授权
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
	                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
	                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
	                	
	                    if(device != null){
	                      //
	                    	Log.d(TAG,"PERMISSION-" + device);
	                    	updateEthInterface();
	                   }
	                }					
	
				}
			}					
	    }
	};	
	
	
	/**
	 * 检测USB插入，是否添加了网卡,更新网卡状态
	 */
	private void  updateEthInterface()
	{
		List<NetInterfaceInfo> mTempList=Utils.getInstance().getNetInterface();
    	for(NetInterfaceInfo iter:mTempList)
    	{
    		if(findInterfaceByName(iter.getIfName(),mListEthInterface)==null)
    		//if(!mListEthInterface.contains(iter))
    		{
    			Utils.debug(TAG, "FIND interface "+iter);
    			
    			mEthInterface=iter;
    			
    			Utils.getInstance().writeEthInterface(MainActivity.this, mEthInterface.getIfName());
    			
    			Preference preList=(Preference)findPreference("enable_eth");
    	
    			preList.setEnabled(true);
    			//preList.setShouldDisableView(false);	
    		    preList.setSummary(String.format(getResources().getString(R.string.find_eth),
    		    									mEthInterface.getIfName()));

    		    setIpInfoSummary(mEthInterface);
    		}
    	}
	}
	
	
	
	/**	
	* 返回当前程序版本名  
	*/
	public static String getAppVersionName(Context context) {   
	    String versionName = "";   
	    try {   
	        // ---get the package info---   
	        PackageManager pm = context.getPackageManager();   
	        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);   
	        versionName = pi.versionName;   
	        if (versionName == null || versionName.length() <= 0) {   
	            return "1.0.0";   
	        }   
	    } catch (Exception e) {   
	        Log.e("VersionInfo", "Exception", e);   
	    }   
	    return versionName;   
	}  
	
	private NetInterfaceInfo findInterfaceByName(String ifName, List<NetInterfaceInfo> ifInfoList)
	{
		for(NetInterfaceInfo ifItem:ifInfoList)
			if(ifItem.getIfName().equals(ifName))
				return ifItem;
		
		return null;
	}
}
